const User = require('../models/User.js');
const { Op } = require('sequelize');

//添加用户
const addUser = async (username, password) => {
  const res = await User.create({
    username,
    password,
  });
  return res.toJSON();
};

//管理员用户管理界面--新增交通部门用户
const addTrafficUser = async (username, password) => {
  const res = await User.create({
    username,
    password,
    userType: '交通部门',
    roleCode: 1,
  });
  return res.toJSON();
};

//根据用户名查询用户
const getUserByUsername = async username => {
  const res = await User.findOne({
    where: {
      username,
    },
  });
  return res ? res.toJSON() : null;
};

//查询所有用户
const getAllUser = async () => {
  const res = await User.findAll();
  return res.map(user => user.toJSON());
};

//根据搜索关键字进行模糊查询
const searchUserLike = async keyword => {
  const res = await User.findAll({
    where: {
      username: {
        [Op.like]: `%${keyword}%`,
      },
    },
  });
  return res.map(user => user.toJSON());
};

//修改用户名和密码
const updateUserById = async (id, username, password) => {
  const user = await User.findOne({
    where: {
      id,
    },
  });

  if (user) {
    await user.update({
      username,
      password,
    });
    return '更新成功';
  } else {
    return '用户不存在';
  }
};

const updateUserStatus = async (username, status) => {
  try {
    const user = await User.findOne({
      where: {
        username,
      },
    });

    if (user) {
      await user.update({
        loginStatus: status,
      });
      return '更新成功';
    } else {
      return '用户不存在';
    }
  } catch (error) {
    console.error('更新用户状态失败:', error);
    return '更新失败';
  }
};

//根据用户名删除用户
const deleteUserByUsername = async username => {
  const res = await User.destroy({
    where: {
      username,
    },
  });
  return res;
};

// 验证用户名、密码和角色状态码是否匹配
const validateUser = async (username, password, roleCode) => {
  const user = await User.findOne({
    where: {
      username,
      password,
      roleCode,
    },
  });
  return user ? user.toJSON() : null;
};

module.exports = {
  addUser,
  addTrafficUser,
  getUserByUsername,
  getAllUser,
  updateUserById,
  searchUserLike,
  updateUserStatus,
  deleteUserByUsername,
  validateUser,
};
